<template>
  <div class="planvisit-main guanwang-bg" style="height: calc(100vh - 124px);border-radius: 10px;">
    <div :style="{paddingTop:100 * (10 / screensStore.bodyHeight) + 'vh',
    paddingLeft:100 * (10 / screensStore.bodyWidth) + 'vw',paddingRight:100 * (10 / screensStore.bodyWidth) + 'vw',
    marginBottom:100 * (10 / screensStore.bodyHeight) + 'vh'}"
         v-if="isEmpty">
      <div class="title-desp">{{ screensStore.selPeriodObj.periodName }}</div>
      <div style="margin-top: 20px">
        <el-form :inline="true" :model="searchData" class="demo-form-inline" style="width: 100%">
          <el-form-item>
            <el-tag
              type="primary"
              effect="dark"
              round
            >
              访问问卷列表
            </el-tag>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchData.nodeName" placeholder="请选择状态" style="width: 200px">
              <el-option label="全部" value="全部" />
              <el-option label="访问员录入" value="访问员录入" />
              <el-option label="QC审核" value="QC审核" />
              <el-option label="厂商审核" value="厂商审核" />
              <el-option label="终审结束" value="终审结束" />
            </el-select>
          </el-form-item>
          <el-form-item label="网点简称">
            <el-input v-model="searchData.outletsName" placeholder="请输入网点简称" />
          </el-form-item>
          <el-form-item label="省市区">
            <el-cascader
              :options="screensStore.proviceList"
              v-model="searchData.addressList"
              :props="{value:'label'}"
              clearable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearchList">查询</el-button>
            <el-button @click="onClearList">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div style="width: 100%;display: flex;justify-content: flex-end;align-items: center">
        <div style="margin-right: 10px">
          <el-button round type="primary" :disabled="!selectChangeUser.length"
          @click="plLiangShen('审批')">批量审批</el-button>
          <el-button round type="danger" :disabled="!selectChangeUser.length"
                     @click="plLiangShen('驳回')">批量驳回</el-button>
          <el-button round type="success" :disabled="!selectChangeUser.length"
                     @click="plLiangShen('转办')">批量转办</el-button>
          <el-button round type="warning" :disabled="!selectChangeUser.length"
                     @click="plLiangShen('委派')">批量委派</el-button>
        </div>
        <down-table-show-sort :tablePropsArr="tablePropsArr" @throwTableProps="getTablePropsList"></down-table-show-sort>
      </div>
      <div>
        <el-table :data="tableData" border style="width: 100%" :tooltip-formatter="tableRowFormatter"
                  :header-cell-style="{ background: 'rgb(250,250,250)'}"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="序号" type="index" :index="indexMethod" width="80px" align="center" />
          <template v-for="item in tablePropsArr">
            <el-table-column  :prop="item.prop" :label="item.label" align="center"
                              :key="item.prop" :width="item?.width ?  item?.width : 'auto'" v-if="item.isHidden">
              <template #default="scope">
                <div v-if="item.prop == 'taskName'">
                  <el-tag
                    v-if="scope.row.taskName == '访问员录入'"
                    type="primary"
                    effect="dark"
                  >
                    {{ scope.row.taskName }}
                  </el-tag>
                  <el-tag
                    v-else-if="scope.row.taskName == 'QC审核'"
                    type="success"
                    effect="dark"
                  >
                    {{ scope.row.taskName }}
                  </el-tag>
                  <el-tag
                    v-else-if="scope.row.taskName == '厂商审核'"
                    type="warning"
                    effect="dark"
                  >
                    {{ scope.row.taskName }}
                  </el-tag>
                  <el-tag
                    v-else-if="scope.row.taskName == '终审结束'"
                    type="danger"
                    effect="dark"
                  >
                    {{ scope.row.taskName }}
                  </el-tag>
                  <el-tag
                    v-else
                    type="danger"
                    effect="dark"
                  >
                    {{ scope.row.taskName }}
                  </el-tag>
                </div>
                <div v-else-if="item.prop == 'staffName'">
                  <div style="cursor: pointer;color: rgb(64,158,255)"
                  @click="openInfoUser(scope.row)">{{scope.row['variables'][item.prop]}}</div>
                </div>
                <div v-else>
                  <div>{{scope.row['variables'][item.prop]}}</div>
                </div>
              </template>
            </el-table-column>
          </template>
          <el-table-column prop="handle" label="操作" align="center" width="180px">
            <template #default="scope">
              <el-button type="primary" link @click="openInputDrawer(0,scope.row)">查看
              </el-button>
              <el-button type="primary" link @click="openInputDrawer(1,scope.row)">审批</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="fixed-row" style="width: 100%;justify-content: center;margin-top: 10px">
          <el-pagination background layout="sizes,prev,pager,next,jumper,total" :total="paging.total"
                         @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
        </div>
      </div>
    </div>
    <div v-else style="width: 100%;height: 100%">
      <el-empty description="请先选择期次">
        <el-button type="primary" @click="toIssueselect">选择期次</el-button>
      </el-empty>
    </div>

    <el-drawer
      v-model="inputDrawer"
      title="数据审核"
      size="90%"
      v-loading="formLoading"
      element-loading-text="审核信息提交中..."
      class="jihua-submit"
      :destroy-on-close="true"
    >

      <el-form ref="refForm" :model="formData" :rules="formDataRules">
        <el-descriptions
          class="margin-top"
          title="202404修订-1.0版本"
          :column="2"
          border
        >
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>网点编号</div>
            </template>
            {{ formData?.outletsCode }}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>调查员编号</div>
            </template>
            {{ formData?.phone }}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>地区</div>
            </template>
            {{ formData?.provinceName }}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>调查结果</div>
            </template>
            <el-form-item prop="checkResult">
              <el-select placeholder="请选择调查结果" v-model="formData.checkResult" clearable
              :disabled="true">
                <el-option label="成功" value="成功"></el-option>
                <el-option label="不成功-关门" value="不成功-关门"></el-option>
                <el-option label="不成功-装修" value="不成功-装修"></el-option>
                <el-option label="不成功-搬迁" value="不成功-搬迁"></el-option>
                <el-option label="不成功-拆迁" value="不成功-拆迁"></el-option>
                <el-option label="不成功-找不到" value="不成功-找不到"></el-option>
                <el-option label="不成功-其他" value="不成功-其他"></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>城市</div>
            </template>
            {{ formData?.cityName }}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>不成功原因</div>
            </template>
            <el-form-item>
              <el-input clearable v-model="formData.failReason" :disabled="true"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>被访店名称</div>
            </template>
            {{ formData?.outletsName }}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>被访店地址</div>
            </template>
            {{ formData?.provinceName + formData?.cityName + (formData?.areaName || '') + (formData?.address || '') }}
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>访店日期</div>
            </template>
            <el-form-item prop="visitTime">
              <el-date-picker
                v-model="formData.visitTime"
                type="date"
                :disabled="true"
                style="width: 100%"
                placeholder="请选择访店日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>天气情况</div>
            </template>
            <el-form-item prop="weather">
              <el-select placeholder="请选择天气情况" v-model="formData.weather" clearable :disabled="true">
                <el-option label="晴天" value="晴天"></el-option>
                <el-option label="多云" value="多云"></el-option>
                <el-option label="阴天" value="阴天"></el-option>
                <el-option label="下雨" value="下雨"></el-option>
                <el-option label="下雪" value="下雪"></el-option>
                <el-option label="雾霾" value="雾霾"></el-option>
                <el-option label="冰雹" value="冰雹"></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>入店时间</div>
            </template>
            <el-form-item prop="enterTime">
              <el-date-picker
                v-model="formData.enterTime"
                type="datetime"
                placeholder="请选择入店时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled="!inputType"
                style="width: 100%"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>离店时间</div>
            </template>
            <el-form-item prop="leaveTime">
              <el-date-picker
                v-model="formData.leaveTime"
                type="datetime"
                placeholder="请选择离店时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled="!inputType"
                style="width: 100%"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-width="180px" label-class-name="my-label">
            <template #label>
              <div>最终总得分</div>
            </template>
            <el-tag
              type="danger"
              effect="dark"
            >
              {{  formData.score || 0 }}分
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-form>
      <div style="display: flex;align-items: center;margin-top: 10px">
        <el-select v-model="wenjuanMode" placeholder="请选择问卷渲染方式"
                   @change="changeToggleMode" style="width: 200px">
          <el-option label="正常模式" value="normal"></el-option>
          <el-option label="表格模式" value="table"></el-option>
        </el-select>
        <el-select v-model="wenjuanModeTixing" placeholder="请选择问卷题型"
                   @change="(val) => changeToggleMode1()" style="width: 200px;margin-left: 20px">
          <el-option label="显示全部题型" value="showAll"></el-option>
          <el-option label="显示错误题型" value="showError"></el-option>
        </el-select>
        <el-button type="primary" style="margin-left: 15px;" @click="openStartJisuan">重新计算分数</el-button>
      </div>
      <!--      渲染问卷-->
      <WuJie name="wenjuanAudit" url="http://129.211.212.235:3005/"></WuJie>

      <template #footer>
        <div style="width: 100%;justify-content: space-between;background: #fff" class="fixed-row">
          <div>
            <el-button type="primary" @click="openFlow">流程查看</el-button>
          </div>
          <div>
            <el-button type="primary" @click="saveSubmit(0)"
                       v-if="showHandleBtn">审批</el-button>
            <el-button type="primary" @click="saveSubmit(1)"
                       v-if="!showHandleBtn">驳回</el-button>
            <el-button type="primary" @click="saveSubmit(3)"
                       v-if="!showHandleBtn">退回</el-button>
            <el-button type="primary" @click="saveSubmit(4)"
                       v-if="!showHandleBtn">委派</el-button>
            <el-button type="primary" @click="saveSubmit(5)"
                       v-if="!showHandleBtn">转办</el-button>
            <el-button @click="inputDrawer = false">返回</el-button>
          </div>
        </div>
      </template>
    </el-drawer>
    <!--      审批-->
    <el-dialog
      v-model="auditVisible"
      width="500"
      :title="!showAuditType ? '审批' : showAuditType == 1 ? '驳回流程' : ''"
      append-to-body
      class="elmessageTip"
      center
    >
      <el-form ref="refAuditForm" :model="auditFormData" :rules="formAuditRules" label-width="auto" >
        <el-form-item :label="!showAuditType ? '处理意见' : showAuditType == 1 ? '驳回意见' : ''" prop="comment">
          <el-input clearable v-model="auditFormData.comment" type="textarea" autosize></el-input>
        </el-form-item>
        <el-form-item>
          <div style="width: 100%;justify-content: center" class="fixed-row">
            <el-button type="primary" @click="saveAudit">确定</el-button>
            <el-button @click="auditVisible = false">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--      退回-->
    <el-dialog :title="returnTitle" v-model="returnOpen" width="500" append-to-body class="tuihui-info"
               center>
      <el-form ref="taskForm" :model="auditFormData" label-width="auto" :rules="formAuditTuiRules">
        <el-form-item label="退回节点" prop="targetKey">
          <el-radio-group v-model="auditFormData.targetKey" style="width: 100%">
            <el-radio-button
              v-for="item in returnTaskList"
              :key="item.id"
              :label="item.id"
            >{{ item.name }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退回意见" prop="comment"
                      :rules="[{ required: true, message: '请输入意见', trigger: 'blur' }]">
          <el-input  type="textarea" v-model="auditFormData.comment" placeholder="请输入意见"
                     autosize/>
        </el-form-item>
        <el-form-item>
          <div style="width: 100%;justify-content: center" class="fixed-row">
            <el-button type="primary" @click="taskReturn">确 定</el-button>
            <el-button @click="returnOpen = false">取 消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--      委派和转办-->
    <el-dialog :title="appointTitle" v-model="appointOpen" width="500" append-to-body class="weipai"
               center>
      <el-form ref="weipaiForm" :model="auditFormData" label-width="auto" :rules="formAuditWeiRules">
        <el-form-item :label="showAuditType == 5 ? '转办人员' : '委派人员'" prop="assigneeName"
                      :rules="[{ required: true, message: '请选择人员', trigger: 'blur' }]">
          <div style="width: 100%" @click="openLeader">
            <el-input v-model="auditFormData.assigneeName"
                      :placeholder="'请选择人员'"
            />
          </div>
        </el-form-item>
        <el-form-item :label="showAuditType == 5 ? '转办' : '委派' + '意见'" prop="comment"
                      :rules="[{ required: true, message: '请输入意见', trigger: 'blur' }]">
          <el-input type="textarea" v-model="auditFormData.comment" placeholder="请输入意见"/>
        </el-form-item>
        <el-form-item>
          <div style="width: 100%;justify-content: center" class="fixed-row">
            <el-button type="primary" @click="taskAppoint">确 定</el-button>
            <el-button @click="appointOpen = false">取 消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <sel-leader-dialog ref="refLeaderDialog" @throwProjectValue="getLeaderDialogValDia"
                       :projectId="auditFormData.assignee" :is-start="false"></sel-leader-dialog>
    <flowview ref="refFlowview" is-type="1" :visitPlanId="formData.hasOwnProperty('variables') ? formData.variables.id : formData.id" auditType="0"></flowview>


    <el-dialog v-model="dialogTableVisible" title="访问员信息" width="600"
    :append-to-body="true">
      <el-descriptions
        class="margin-top"
        :column="1"
        label-width="120"
        border
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon><user /></el-icon>
              访问员状态
            </div>
          </template>
          <el-tag
            v-if="userInfoSet.state == '已审核'"
            type="success"
            effect="dark">
            {{ userInfoSet.state }}
          </el-tag>
          <el-tag
            v-else-if="userInfoSet.state == '已启用'"
            type="success"
            effect="dark">
            {{ userInfoSet.state }}
          </el-tag>
          <el-tag
            v-else-if="userInfoSet.state == '已停用'"
            type="danger"
            effect="dark">
            {{ userInfoSet.state }}
          </el-tag>
          <el-tag
            v-else-if="userInfoSet.state == '已拒绝'"
            type="danger"
            effect="dark">
            {{ userInfoSet.state }}
          </el-tag>
          <el-tag
            v-else
            type="danger"
            effect="dark">
            {{ userInfoSet.state }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon><user /></el-icon>
              访问员名称
            </div>
          </template>
          {{userInfoSet.staffName}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon><Iphone /></el-icon>
              访问员电话
            </div>
          </template>
          {{userInfoSet.mobile}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon><LocationInformation /></el-icon>
              访问员地址
            </div>
          </template>
          {{userInfoSet.provinceName + userInfoSet.cityName + userInfoSet.areaName + (userInfoSet.address || '')}}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
  import { screenStore } from '~/stores/modules/screen'
  import { onMounted,ref,reactive,nextTick } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import {getDataAuditList,complete,rejectTask,returnTask,returnList,appointPeo,zhuanPeo} from '~/api/dataaudit'
  import {getTableLocail,setTableLocail,getDetail,taskAllAudit,toggleMode,jisuanScore,getUserInfo,getErrorCuOTi} from '~/api/public'
  let periodId = ''
  let yuanWenjuanJSON = ''
  const auditObj = {}
  const screensStore = screenStore()
  const route = useRoute()
  const router = useRouter()
  const refFlowview = ref()
  const isEmpty = ref(false)
  const showAuditType = ref(0)
  const refAuditForm = ref()
  const refLeaderDialog = ref()
  const dialogTableVisible = ref(false)
  const inputDrawer = ref(false)
  const formLoading = ref(false)
  const auditVisible = ref(false)
  const returnTitle = ref('')
  const appointTitle = ref('')
  const appointOpen = ref(false)
  const returnOpen = ref(false)
  const tableData = ref([])
  const taskForm = ref()
  const weipaiForm = ref()
  const returnTaskList = ref([])
  const selectChangeUser = ref([])
  const paging = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })
  const wenjuanModeTixing = ref('showAll')
  const userInfoSet = reactive({})
  const removeCharAt = (str, index) => {
    return str.slice(0, index) + str.slice(index + 1);
  }
  const searchData = reactive({
    nodeName: '',
    outletsName: '',
    provinceName:'',
    cityName:'',
    areaName:'',
    addressList: []
  })
  const formData = reactive({})
  const auditFormData = reactive({
    comment:'',
    targetKey:'',
    assigneeName:'',
    assignee:'',
  })
  const tablePropsArr = ref([
    {
      prop:'taskName',
      label:'审核状态',
      width:'120px',
      isHidden:true,
      slotRender:(row) => {
        return (
          `<el-tag
                type="primary"
                effect="dark"
            >
              ${row.taskName}
            </el-tag>`
        )
      }
    },
    {
      prop:'staffName',
      label:"访问员名称",
      isHidden: true
    },
    {
      prop:'outletsCode',
      label:'网点编号',
      isHidden:true,
    },
    {
      prop:'outletsName',
      label:'网点简称',
      isHidden:true,
    },
    {
      prop:'commitTime',
      label:'样本最终提交时间',
      isHidden:true,
    },
    {
      prop:'provinceName',
      label:'省份',
      isHidden:true,
    },
    {
      prop:'cityName',
      label: '城市',
      isHidden:true,
    },
    {
      prop:'areaName',
      label:'区县',
      isHidden:true,
    },
    {
      prop:'score',
      label:'样本总得分',
      isHidden:true,
    }
  ])
  const formAuditRules = {
    comment:[{required:true,message:'请输入意见',trigger:'blur'}],
  }
  const formAuditTuiRules = {
    comment:[{required:true,message:'请输入意见',trigger:'blur'}],
    targetKey:[{required:true,message:'请选择节点',trigger:'change'}]
  }
  const formAuditWeiRules = {
    comment:[{required:true,message:'请输入意见',trigger:'blur'}],
    assigneeName:[{required:true,message:'请选择人员信息',trigger:'blur'}]
  }

  let branchAudit = 0
  const formDataRules = {}
  onMounted(() => {
    if (route.query.periodId) {
      isEmpty.value = true
      periodId = route.query.periodId
      getTableList()
    } else {
      isEmpty.value = false
    }
    getTableLocail('dataaudit').then(res => {
      if(res.code == 200){
        tablePropsArr.value = JSON.parse(res.data.fieldJson)
      }
      else{
        tablePropsArr.value = [
          {
            prop:'taskName',
            label:'审核状态',
            width:'120px',
            isHidden:true,
            slotRender:(row) => {
              return (
                `<el-tag
                type="primary"
                effect="dark"
            >
              ${row.taskName}
            </el-tag>`
              )
            }
          },
          {
            prop:'staffName',
            label:"访问员名称",
            isHidden: true
          },
          {
            prop:'outletsCode',
            label:'网点编号',
            isHidden:true,
          },
          {
            prop:'outletsName',
            label:'网点简称',
            isHidden:true,
          },
          {
            prop:'commitTime',
            label:'样本最终提交时间',
            isHidden:true,
          },
          {
            prop:'provinceName',
            label:'省份',
            isHidden:true,
          },
          {
            prop:'cityName',
            label: '城市',
            isHidden:true,
          },
          {
            prop:'areaName',
            label:'区县',
            isHidden:true,
          },
          {
            prop:'score',
            label:'样本总得分',
            isHidden:true,
          }
        ]
      }
    })
  })
  const wenjuanMode = ref('normal')

  function openInfoUser(row){
    getUserInfo(row.variables.staffId,'.planvisit-main').then(res => {
      if(res.data){
        dialogTableVisible.value = true
        Object.assign(userInfoSet,{
          ...res.data
        })
      }
      else{
        ElMessage.error('该访问员暂无信息！无法查看')
      }

    })
  }

  function changeToggleMode1(json1 = ''){
    const json = JSON.stringify(json1 || yuanWenjuanJSON)
    let type = null
    if(wenjuanModeTixing.value == 'showAll'){
      type = 1
    }
    else{
      type = 0
    }
    getErrorCuOTi({json,type}).then(res => {
      if(res.code == 200){
        wenjuanJson.value = JSON.parse(res.data)
        if(!type){
          const arrRendJson = []
          const arrJson = JSON.parse(res.data)
          for(let val of arrJson){
            let obj = JSON.parse(val)
            obj.formGlobalConf.emptyText = '当前问题组暂无错题'
            arrRendJson.push(JSON.stringify(obj))
            continue
          }
          wenjuanJson.value = arrRendJson
        }
        setTimeout(()=>{
          window.document.querySelector("iframe[name=wenjuanAudit]").contentWindow.setWenJsonValue(wenjuanJson.value,showHandleBtn.value ? 'xiezuo' : 'yulan',showHandleBtn.value ? 'xiezuo' : 'yulan',
            screensStore.roles);
        },1000)
      }
      else{
        ElMessage.error(res.msg || '切换失败')
      }
    })
  }
  function changeToggleMode(){
    const data = {
      json:JSON.stringify(wenjuanJson.value),
      type:wenjuanMode.value
    }
    toggleMode(data,'.jihua-submit').then(res => {
      if(res.code == 200){
        ElMessage.success('问卷模式切换成功')
        setTimeout(()=>{
          window.document.querySelector("iframe[name=wenjuanAudit]").contentWindow.setWenJsonValue(JSON.parse(res.data),showHandleBtn.value ? 'xiezuo' : 'yulan',showHandleBtn.value ? 'xiezuo' : 'yulan',
          screensStore.roles);
        },1000)
      }
    })
  }

  function openStartJisuan(){
    const data = {
      id:formData.variables.id,
    }
    window.document.querySelector('iframe[name=wenjuanAudit]').contentWindow.getWenJuanValue().then(result => {
      data.questJson = JSON.stringify(result)
      if(wenjuanModeTixing.value == 'showError'){
        // 说明当前选择是错误
        const editWen = JSON.parse(data.questJson)
        const cloneYuanJson = [...yuanWenjuanJSON]
        for(let i = 0;i < cloneYuanJson.length;i++){
          let yuanItemWen = JSON.parse(cloneYuanJson[i])
          let editItemWen = JSON.parse(editWen[i])
          for(let val of editItemWen.containerConfigList){
            const ind1 = yuanItemWen.containerConfigList.findIndex(item => item.id == val.id)
            const ind2 = editItemWen.containerConfigList.findIndex(item => item.id == yuanItemWen.containerConfigList[ind1].id)
            if(ind1 != -1){ //查到了当前问题组内有错题
              for(let childVal of yuanItemWen.containerConfigList[ind1].widgetList){
                const childInd = editItemWen.containerConfigList[ind2].widgetList.findIndex(item => item.id == childVal.id)
                const childIndYuan = yuanItemWen.containerConfigList[ind1].widgetList.findIndex(item => item.id == editItemWen.containerConfigList[ind2].widgetList[childInd].id)
                if(childInd != -1){
                  //拿出了当前得错题并替换掉
                  yuanItemWen.containerConfigList[ind1].widgetList[childIndYuan] = editItemWen.containerConfigList[ind2].widgetList[childInd]
                  continue
                }
                else{
                  continue
                }
              }
            }
          }
        }
        data.questJson = JSON.stringify(cloneYuanJson)
      }
      jisuanScore(data,'.jihua-submit').then(res => {
        if(res.code == 200){
          ElMessage.success('分数计算成功')
          if(wenjuanModeTixing.value == 'showError'){
            yuanWenjuanJSON = JSON.parse(res.data) //重新赋值有错误题修改后的原题型
            changeToggleMode1(JSON.parse(res.data))
          }
          else{
            wenjuanJson.value = JSON.parse(res.data)
            setTimeout(()=>{
              window.document.querySelector("iframe[name=wenjuanAudit]").contentWindow.setWenJsonValue(wenjuanJson.value,showHandleBtn.value ? 'xiezuo' : 'yulan',showHandleBtn.value ? 'xiezuo' : 'yulan',
                screensStore.roles);
            },1000)
          }
        }
      })
    })
  }
  const handleSelectionChange = (rows) => {
    selectChangeUser.value = [...rows]
  }
  const getTablePropsList = (tablePropsArrs) => {
    tablePropsArr.value = tablePropsArrs
    const data = {
      name:'dataaudit',
      fieldJson:JSON.stringify(tablePropsArr.value)
    }
    setTableLocail(data)
  }
  function openLeader() {
    refLeaderDialog.value.openProjectDia()
  }
  // 去往期次选择页面
  function toIssueselect() {
    screensStore.activeHomeNav = '期次选择'
    router.replace({ path: '/issueselect' })
  }
  const tableRowFormatter = (data) => {
    return `${data.cellValue}`
  }

  const plLiangShen = (type) => {
    branchAudit = 0
    ElMessageBox.confirm(`是否确认开始批量审核`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        auditFormData.comment = ''
        auditFormData.targetKey = ''
        auditFormData.assigneeName = ''
        auditFormData.assignee = ''
        if(type == '审批'){
          auditVisible.value = true
          showAuditType.value = 0
        }
        else if(type == '驳回'){
          auditVisible.value = true
          showAuditType.value = 1
        }
        else if(type == '转办'){
          appointOpen.value = true
          appointTitle.value = '转办'
          showAuditType.value = 5
        }
        else{
          // 委派
          appointOpen.value = true
          appointTitle.value = '委派'
          showAuditType.value = 4
        }
      })

  }
  /** 提交退回任务 */
  async function taskReturn() {
    await taskForm.value.validate(valid => {
      if (valid) {
        const data = {}
        Object.assign(data,{
          ...auditObj,
          ...auditFormData,
        })
        data.instanceId = data.procInsId
        returnTask(data).then(res => {
          if(res.code == 200){
            ElMessage({
              type:'success',
              appendTo:'.tuihui-info',
              message:'退回成功'
            })
            returnOpen.value = false
            inputDrawer.value = false
            getTableList()
          }
          else{
            ElMessage({
              type:'error',
              appendTo:'.tuihui-info',
              message:res.msg
            })
          }
        });
      }
    });
  }
  function getTableList(){
    const params = {
      ...searchData,
      pageNum:paging.currentPage,
      pageSize:paging.pageSize,
      periodId:periodId,
      category:'审核流程'
    }
    delete params.addressList
    getDataAuditList(params).then(res => {
      if(res.code == 200){
        paging.total = res.data.total * 1
        tableData.value = res.data.records
      }
      else{
        tableData.value = []
        paging.total = 0
      }
    })
  }
  function handleSizeChange(val){
    paging.pageSize = val
    getTableList()
  }
  function handleCurrentChange(val){
    paging.currentPage = val
    getTableList()
  }
  function onSearchList() {
    if(searchData.addressList.length){
      searchData.provinceName = searchData.addressList[0]
      searchData.cityName = searchData.addressList[1]
      searchData.areaName = searchData.addressList[2]
    }
    else{
      searchData.provinceName = ''
      searchData.cityName = ''
      searchData.areaName = ''
    }
    paging.currentPage = 1
    getTableList()
  }

  function onClearList() {
    Object.assign(searchData,{
      nodeName: '',
      outletsName: '',
      provinceName:'',
      cityName:'',
      areaName:'',
      addressList: []
    })
    paging.currentPage = 1
    getTableList()
  }

  function indexMethod(index: number) {
    return (paging.currentPage - 1) * paging.pageSize + index + 1
  }
  const showHandleBtn = ref(false)
  const wenjuanJson = ref('')
  function openInputDrawer(type, row) {
    branchAudit = 1
    inputDrawer.value = true
    wenjuanMode.value = 'normal'
    wenjuanModeTixing.value = 'showAll'
    if(!type){
      showHandleBtn.value = false
    }
    if(type == 1){
      showHandleBtn.value = true
    }
    Object.assign(auditObj,{
      ...row
    })
    Object.assign(formData,{
      ...row,
      ...row.variables
    })
    formData.periodId = periodId

    getDetail(row.variables.id).then(res => {
      if (res.code == 200) {
        if (res.data.id) {
          Object.assign(auditObj,{
            ...row
          })
          Object.assign(formData, {
            ...res.data
          })
        }
        inputDrawer.value = true
        if (!res.data.questJson) {
          wenjuanJson.value = ''
          yuanWenjuanJSON = ''
        } else {
          wenjuanJson.value = JSON.parse(res.data.questJson)
          yuanWenjuanJSON = JSON.parse(res.data.questJson)
        }
        nextTick(()=>{
          if(window.document.querySelector("iframe[name=wenjuanAudit]").contentWindow.setWenJsonValue){
            setTimeout(()=>{
              window.document.querySelector("iframe[name=wenjuanAudit]").contentWindow.setWenJsonValue(wenjuanJson.value,showHandleBtn.value ? 'xiezuo' : 'yulan',showHandleBtn.value ? 'xiezuo' : 'yulan',
                screensStore.roles);
            },1000)
          }
          else{
            setTimeout(()=>{
              window.document.querySelector("iframe[name=wenjuanAudit]").contentWindow.setWenJsonValue(wenjuanJson.value,showHandleBtn.value ? 'xiezuo' : 'yulan',showHandleBtn.value ? 'xiezuo' : 'yulan',
                screensStore.roles);
            },1000)
          }
        })
      }
    })
  }

  function saveSubmit(type) {
    auditFormData.comment = ''
    auditFormData.targetKey = ''
    auditFormData.assigneeName = ''
    auditFormData.assignee = ''
    showAuditType.value = type * 1
    if(!type || type == 1){
      auditVisible.value = true
    }
    if(type == 3){
      returnOpen.value = true
      returnTitle.value = "退回流程";
      returnList(auditObj).then(res => {
        returnTaskList.value = res.data;
      })
    }
    if(type == 4 || type == 5){
      appointOpen.value = true
      if(type == 4){
        appointTitle.value = '委派人员'
      }
      else{
        appointTitle.value = '转办任务'
      }
    }
  }

  async function saveAudit(){
    if(branchAudit){
      await refAuditForm.value.validate((bol)=>{
        if(bol){
          //todo 调取审核接口
          const data = {}
          Object.assign(data,{
            ...auditObj,
            comment:auditFormData.comment,
          })
          try{
            window.document.querySelector('iframe[name=wenjuanAudit]').contentWindow.getWenJuanValue().then(result => {
              data.variables.questJson = JSON.stringify(result)
              if(wenjuanModeTixing.value == 'showError'){
                // 说明当前选择是错误
                const editWen = JSON.parse(data.variables.questJson)
                const cloneYuanJson = [...yuanWenjuanJSON]
                for(let i = 0;i < cloneYuanJson.length;i++){
                  let yuanItemWen = JSON.parse(cloneYuanJson[i])
                  let editItemWen = JSON.parse(editWen[i])
                  for(let val of editItemWen.containerConfigList){
                    const ind1 = yuanItemWen.containerConfigList.findIndex(item => item.id == val.id)
                    const ind2 = editItemWen.containerConfigList.findIndex(item => item.id == yuanItemWen.containerConfigList[ind1].id)
                    if(ind1 != -1){ //查到了当前问题组内有错题
                      for(let childVal of yuanItemWen.containerConfigList[ind1].widgetList){
                        const childInd = editItemWen.containerConfigList[ind2].widgetList.findIndex(item => item.id == childVal.id)
                        const childIndYuan = yuanItemWen.containerConfigList[ind1].widgetList.findIndex(item => item.id == editItemWen.containerConfigList[ind2].widgetList[childInd].id)
                        if(childInd != -1){
                          //拿出了当前得错题并替换掉
                          yuanItemWen.containerConfigList[ind1].widgetList[childIndYuan] = editItemWen.containerConfigList[ind2].widgetList[childInd]
                          continue
                        }
                        else{
                          continue
                        }
                      }
                    }
                  }
                }
                data.variables.questJson = JSON.stringify(cloneYuanJson)
              }

              data.instanceId = data.procInsId
              data.variables.approve = screensStore.user.userId
              // 审批
              if(!showAuditType.value){
                // 审批
                complete(data).then(res => {
                  if(res.code == 200){
                    ElMessage({
                      type:'success',
                      appendTo:'.elmessageTip',
                      message:'审批成功'
                    })
                    auditVisible.value = false
                    inputDrawer.value = false
                    getTableList()
                  }
                  else{
                    ElMessage({
                      type:'error',
                      appendTo:'.elmessageTip',
                      message:res.msg
                    })
                  }
                })
              }
              else if(showAuditType.value == 1){
                // 驳回
                rejectTask(data).then(res => {
                  if(res.code == 200){
                    ElMessage({
                      type:'success',
                      appendTo:'.elmessageTip',
                      message:'驳回成功'
                    })
                    auditVisible.value = false
                    inputDrawer.value = false
                    getTableList()
                  }
                  else{
                    ElMessage({
                      type:'error',
                      appendTo:'.elmessageTip',
                      message:res.msg
                    })
                  }
                })
              }
            })
          }catch (e) {
            ElMessage({
              type:"error",
              message:'出现问题请联系管理员',
              appendTo:'.elmessageTip',
            })
          }
        }
      })
    }
    else{
      try{
        if(!showAuditType.value){
          selectChangeUser.value.forEach(item => {
            item.comment = auditFormData.comment
            item.variables.approve = screensStore.user.userId
            item.assigneeType = '审批'
            item.instanceId = item.procInsId
          })
          taskAllAudit(selectChangeUser.value,'.elmessageTip','审批中').then(res => {
            if(res.code == 200){
              ElMessage({
                type:'success',
                appendTo:'.elmessageTip',
                message:'审批成功'
              })
              auditVisible.value = false
              selectChangeUser.value = []
              getTableList()
            }
            else{
              ElMessage({
                type:'error',
                appendTo:'.elmessageTip',
                message:res.msg
              })
            }
          })
        }
        else if(showAuditType.value == 1){
          // 驳回
          selectChangeUser.value.forEach(item => {
            item.comment = auditFormData.comment
            item.variables.approve = screensStore.user.userId
            item.assigneeType = '驳回'
            item.instanceId = item.procInsId
          })
          taskAllAudit(selectChangeUser.value,'.elmessageTip','驳回中').then(res => {
            if(res.code == 200){
              ElMessage({
                type:'success',
                appendTo:'.elmessageTip',
                message:'审批成功'
              })
              auditVisible.value = false
              selectChangeUser.value = []
              getTableList()
            }
            else{
              ElMessage({
                type:'error',
                appendTo:'.elmessageTip',
                message:res.msg
              })
            }
          })
        }
      }catch (e) {
        ElMessage({
          type:"error",
          message:'出现问题请联系管理员',
          appendTo:'.elmessageTip',
        })
      }
    }

  }

  function getLeaderDialogValDia(list) {
    if (list.length > 0) {
      auditFormData.assigneeName = ''
      auditFormData.assignee = ''
      for (let val of list) {
        auditFormData.assigneeName += val['nickName'] + ','
        auditFormData.assignee += val['userId'] + ','
        continue
      }
      if (auditFormData.assigneeName[auditFormData.assigneeName.length - 1] == ',') {
        auditFormData.assigneeName = removeCharAt(auditFormData.assigneeName, auditFormData.assigneeName.length - 1)
      }
      if (auditFormData.assignee[auditFormData.assignee.length - 1] == ',') {
        auditFormData.assignee = removeCharAt(auditFormData.assignee, auditFormData.assignee.length - 1)
      }
    } else {
      auditFormData.assigneeName = ''
      auditFormData.assignee = ''
    }
  }

  async function taskAppoint() {
    await weipaiForm.value.validate(valid => {
      if (valid) {
        if(branchAudit){
          const data = {}
          Object.assign(data,{
            ...auditObj,
            ...auditFormData
          })
          data.instanceId = data.procInsId
          if (showAuditType.value == 4) {
            appointPeo(data).then(res => {
              if(res.code == 200){
                ElMessage({
                  type:'success',
                  appendTo:'.weipai',
                  message:'委派成功'
                })
                appointOpen.value = false
                inputDrawer.value = false
                getTableList()
              }
              else{
                ElMessage({
                  type:'error',
                  appendTo:'.weipai',
                  message:res.msg
                })
              }
            });
          }
          else {
            zhuanPeo(data).then(res => {
              if(res.code == 200){
                ElMessage({
                  type:'success',
                  appendTo:'.weipai',
                  message:'转办成功'
                })
                appointOpen.value = false
                inputDrawer.value = false
                getTableList()
              }
              else{
                ElMessage({
                  type:'error',
                  appendTo:'.weipai',
                  message:res.msg
                })
              }
            });
          }
        }
        else{
          selectChangeUser.value.forEach(item => {
            Object.assign(item,{
              ...item,
              ...auditFormData,
              instanceId:item.procInsId
            })
          })
          if (showAuditType.value == 4) {
            taskAllAudit(selectChangeUser.value,'.weipai','委派中').then(res => {
              if(res.code == 200){
                ElMessage({
                  type:'success',
                  appendTo:'.weipai',
                  message:'委派成功'
                })
                appointOpen.value = false
                selectChangeUser.value = []
                getTableList()
              }
              else{
                ElMessage({
                  type:'error',
                  appendTo:'.elmessageTip',
                  message:res.msg
                })
              }
            })
          }
          else{
            taskAllAudit(selectChangeUser.value,'.weipai','转办中').then(res => {
              if(res.code == 200){
                ElMessage({
                  type:'success',
                  appendTo:'.weipai',
                  message:'转办成功'
                })
                appointOpen.value = false
                selectChangeUser.value = []
                getTableList()
              }
              else{
                ElMessage({
                  type:'error',
                  appendTo:'.elmessageTip',
                  message:res.msg
                })
              }
            })
          }
        }

      }
    });
  }

  function openFlow(){
    refFlowview.value.openFlowDrawer()
  }
</script>

<style scoped lang="less">
  .title-desp {
    font-size: 18px;
    color: #666;
    font-weight: 700;
  }

  .margin-top ::v-deep .el-descriptions__body .el-descriptions__table.is-bordered .el-descriptions__cell .el-form-item {
    margin-bottom: 0;
  }
</style>
